﻿using System;
using System.Collections.Generic;
using System.Text;
using RabbitMQDemo.Common;

namespace RabbitMQDemo.Producer
{
    public class Priority
    {
        private const string ExchangeName = "priority_exchange";

        private const string QueueName = "priority_queue";

        private const string RoutingKey = "priority_routing";

        public static void Send(string[] args)
        {
            using var connection = MQClient.GetConnection();
            using var channel = connection.CreateModel();

            // 声明交换机
            channel.ExchangeDeclare(exchange: ExchangeName, type: "direct", durable: false, autoDelete: false, arguments: null);

            // 声明队列
            channel.QueueDeclare(queue: QueueName, durable: false, exclusive: false, autoDelete: false, arguments: new Dictionary<string, object> {
                { "x-max-priority", 10 } // 最大优先级，必须设置，否则消息优先级不生效
            });
            channel.QueueBind(queue: QueueName, exchange: ExchangeName, routingKey: RoutingKey, arguments: null);

            var index = 0;
            while (index < 10)
            {
                // 设置消息优先级
                var properties = channel.CreateBasicProperties();
                properties.Priority = (byte)new Random().Next(0, 100);

                // 发送消息
                channel.BasicPublish(exchange: ExchangeName, routingKey: RoutingKey, mandatory: false, basicProperties: properties, body: GetMessage(index));

                // Thread.Sleep(1000);
                Console.WriteLine($"[{index}]Send priority message. priority={properties.Priority}");
                index++;
            }
        }

        private static byte[] GetMessage(int? i = null) => Encoding.UTF8.GetBytes($"[Priority]{(i.HasValue ? $"[{i}]" : string.Empty)} message");
    }
}
